package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.IJtOrderOperateLogService;
import com.ruoyi.business.service.IJtOrderService;
import com.ruoyi.business.service.IJtProductService;
import com.ruoyi.business.utils.SnGenerateUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.mapper.JtOutboundOrderMapper;
import com.ruoyi.business.service.IJtOutboundOrderService;
import com.ruoyi.common.core.text.Convert;

/**
 * 出库单Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-06-19
 */
@Service
public class JtOutboundOrderServiceImpl implements IJtOutboundOrderService 
{
    @Autowired
    private JtOutboundOrderMapper jtOutboundOrderMapper;
    @Autowired
    private IJtOrderService jtOrderService;
    @Autowired
    private IJtProductService jtProductService;
    @Autowired
    private IJtOrderOperateLogService jtOrderOperateLogService;

    /**
     * 查询出库单
     * 
     * @param outboundOrderId 出库单主键
     * @return 出库单
     */
    @Override
    public JtOutboundOrder selectJtOutboundOrderByOutboundOrderId(Long outboundOrderId)
    {
        return jtOutboundOrderMapper.selectJtOutboundOrderByOutboundOrderId(outboundOrderId);
    }

    /**
     * 查询出库单列表
     * 
     * @param jtOutboundOrder 出库单
     * @return 出库单
     */
    @Override
    public List<JtOutboundOrder> selectJtOutboundOrderList(JtOutboundOrder jtOutboundOrder)
    {
        return jtOutboundOrderMapper.selectJtOutboundOrderList(jtOutboundOrder);
    }

    /**
     * 新增出库单
     * 
     * @param jtOutboundOrder 出库单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertJtOutboundOrder(JtOutboundOrder jtOutboundOrder)
    {
        jtOutboundOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
        jtOutboundOrder.setCreateTime(DateUtils.getNowDate());
        int rows = jtOutboundOrderMapper.insertJtOutboundOrder(jtOutboundOrder);
        insertJtOutboundOrderItem(jtOutboundOrder);
        return rows;
    }

    /**
     * 修改出库单
     * 
     * @param jtOutboundOrder 出库单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtOutboundOrder(JtOutboundOrder jtOutboundOrder)
    {
        jtOutboundOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtOutboundOrder.setUpdateTime(DateUtils.getNowDate());
        jtOutboundOrderMapper.deleteJtOutboundOrderItemByOutboundOrderId(jtOutboundOrder.getOutboundOrderId());
        insertJtOutboundOrderItem(jtOutboundOrder);
        return jtOutboundOrderMapper.updateJtOutboundOrder(jtOutboundOrder);
    }

    /**
     * 修改出库单
     *
     * @param jtOutboundOrder 出库单
     * @return 结果
     */
    public int updateJtOutboundOrderData(JtOutboundOrder jtOutboundOrder)
    {
        jtOutboundOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtOutboundOrder.setUpdateTime(DateUtils.getNowDate());
        return jtOutboundOrderMapper.updateJtOutboundOrder(jtOutboundOrder);
    }

    /**
     * 批量删除出库单
     * 
     * @param outboundOrderIds 需要删除的出库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtOutboundOrderByOutboundOrderIds(String outboundOrderIds)
    {
        jtOutboundOrderMapper.deleteJtOutboundOrderItemByOutboundOrderIds(Convert.toStrArray(outboundOrderIds));
        return jtOutboundOrderMapper.deleteJtOutboundOrderByOutboundOrderIds(Convert.toStrArray(outboundOrderIds));
    }

    /**
     * 删除出库单信息
     * 
     * @param outboundOrderId 出库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtOutboundOrderByOutboundOrderId(Long outboundOrderId)
    {
        jtOutboundOrderMapper.deleteJtOutboundOrderItemByOutboundOrderId(outboundOrderId);
        return jtOutboundOrderMapper.deleteJtOutboundOrderByOutboundOrderId(outboundOrderId);
    }

    /**
     * 新增出库单明细信息
     * 
     * @param jtOutboundOrder 出库单对象
     */
    public void insertJtOutboundOrderItem(JtOutboundOrder jtOutboundOrder)
    {
        List<JtOutboundOrderItem> jtOutboundOrderItemList = jtOutboundOrder.getJtOutboundOrderItemList();
        Long outboundOrderId = jtOutboundOrder.getOutboundOrderId();
        if (StringUtils.isNotNull(jtOutboundOrderItemList))
        {
            List<JtOutboundOrderItem> list = new ArrayList<JtOutboundOrderItem>();
            for (JtOutboundOrderItem jtOutboundOrderItem : jtOutboundOrderItemList)
            {
                jtOutboundOrderItem.setOutboundOrderId(outboundOrderId);
                jtOutboundOrderItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                jtOutboundOrderItem.setCreateTime(DateUtils.getNowDate());
                list.add(jtOutboundOrderItem);
            }
            if (list.size() > 0)
            {
                jtOutboundOrderMapper.batchJtOutboundOrderItem(list);
            }
        }
    }


    /**
     *  确认出库
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public AjaxResult outboundByIds(String ids){
        if(StringUtils.isEmpty(ids)){
            return AjaxResult.error("请选择入库单");
        }
        String[] idArray = Convert.toStrArray(ids);
        for(String idItem: idArray) {
            JtOutboundOrder outboundOrder = selectJtOutboundOrderByOutboundOrderId(Long.valueOf(idItem));

            if (outboundOrder.getStatus() != 0) {
                return AjaxResult.error("此状态不能出库");
            }

            for(JtOutboundOrderItem outboundOrderItem : outboundOrder.getJtOutboundOrderItemList()){
                JtProduct productParam = new JtProduct();
                productParam.setStyleNo(outboundOrderItem.getStyleNo());
                productParam.setProductCode(outboundOrderItem.getProductCode());
                List<JtProduct> productList = jtProductService.selectJtProductList(productParam);
                JtProduct jtProductDb = productList.get(0);
                if(jtProductDb.getStock() == 0 || jtProductDb.getStock() < outboundOrderItem.getQty()){
                    throw new BaseException(jtProductDb.getProductCode() +"库存不足："+jtProductDb.getStock());
                }
                //计算更新库存
                Long d = jtProductDb.getStock() - outboundOrderItem.getQty();
                JtProduct product = new JtProduct();
                product.setStock(d);
                product.setProductId(jtProductDb.getProductId());
                int rows = jtProductService.updateJtProduct(product);
                if(rows > 0){

                } else {
                    throw new BaseException("商品编码："+jtProductDb.getProductCode() +"库存更新失败！");
                }
            }
            outboundOrder.setOutboundDate(DateUtils.getNowDate());
            outboundOrder.setStatus(1);
            int rows = updateJtOutboundOrderData(outboundOrder);
            if(rows > 0){

            } else {
                throw new BaseException("出库单号："+outboundOrder.getOutboundOrderNo() +"库存更新失败！");
            }
        }
        return AjaxResult.success("出库成功！");
    }


    /**
     * 订单出库
     * @param orderId
     * @return
     */
    @Transactional
    @Override
    public AjaxResult outboundByOrderId(Long orderId){
        JtOrder order = jtOrderService.selectJtOrderByOrderId(orderId);
        if(order.getIsPayed() != 1){
            return AjaxResult.error("订单未付款");
        }
        if(order.getOrderStatus() != 1){
            return AjaxResult.error("该订单状态不能出库");
        }

        if(order.getJtOrderItemList() == null || order.getJtOrderItemList().size() == 0){
            return AjaxResult.error("未找到订单明细");
        }

        Long totalQty = 0L;
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<JtOutboundOrderItem> outboundOrderItemList = new ArrayList<>();
        for (JtOrderItem item: order.getJtOrderItemList()){
            JtProduct productParam = new JtProduct();
            productParam.setStyleNo(item.getStyleNo());
            productParam.setProductCode(item.getSkuCode());
            List<JtProduct> productList = jtProductService.selectJtProductList(productParam);
            if(productList.size() ==0){
                throw new BaseException(item.getSkuCode() +" 未找到产品");
            }
            JtProduct jtProductDb = productList.get(0);
            if(jtProductDb.getStock() <= 0 || jtProductDb.getStock() < item.getProdCount()){
                throw new BaseException(jtProductDb.getProductCode() +"库存不足："+jtProductDb.getStock());
            }
            totalQty += item.getProdCount();
            BigDecimal amount = jtProductDb.getCost().multiply(BigDecimal.valueOf(item.getProdCount()));
            totalAmount = totalAmount.add(amount);

            JtOutboundOrderItem outboundOrderItem = new JtOutboundOrderItem();
            outboundOrderItem.setStyleNo(item.getStyleNo());
            outboundOrderItem.setProductCode(item.getSkuCode());
            outboundOrderItem.setProductId(item.getProductId());
            outboundOrderItem.setUnitPrice(jtProductDb.getCost());
            outboundOrderItem.setAmount(amount);
            outboundOrderItem.setQty(item.getProdCount());
            outboundOrderItemList.add(outboundOrderItem);

            //计算更新库存
            Long d = jtProductDb.getStock() - item.getProdCount();
            JtProduct product = new JtProduct();
            product.setStock(d);
            product.setProductId(jtProductDb.getProductId());
            jtProductService.updateJtProduct(product);
        }
        JtOutboundOrder outboundOrder = new JtOutboundOrder();
        outboundOrder.setDocumentDate(DateUtils.getNowDate());
        outboundOrder.setOutboundOrderNo(SnGenerateUtil.outboundOrderNumber());
        outboundOrder.setOutboundType(2);
        outboundOrder.setRelOrderNo(order.getOrderNo());
        outboundOrder.setStatus(1);
        outboundOrder.setTotalQty(totalQty);
        outboundOrder.setTotalAmount(totalAmount);
        outboundOrder.setWarehouseId(order.getWarehouseId());
        outboundOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
        outboundOrder.setJtOutboundOrderItemList(outboundOrderItemList);
        int rows = insertJtOutboundOrder(outboundOrder);
        if(rows > 0){
            JtOrderOperateLog jtOrderOperateLog = new JtOrderOperateLog();
            jtOrderOperateLog.setOperator(ShiroUtils.getSysUser().getUserName());
            jtOrderOperateLog.setOrderStatus(5);//出库
            jtOrderOperateLog.setNote("出库单:"+outboundOrder.getOutboundOrderNo());
            jtOrderOperateLog.setOrderId(order.getOrderId());
            jtOrderOperateLogService.insertJtOrderOperateLog(jtOrderOperateLog);

            return AjaxResult.success("出库成功");
        } else {
            return AjaxResult.error("出库失败");
        }
    }
}
